<?php

namespace app\api\controller\baiying;


use app\common\exception\UploadException;
use think\Config;
use think\Hook;
use baiying\lib\BYTokenClient;
use think\Db;

/**
 * 公共接口
 */
class Byaiphone extends Bybase {

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize() {
        parent::_initialize();
    }
    
    public function autoFenYeGetTaskPhone(){
        $baiying_api_version = config('zhongzhuan.baiying_api_version');
        $request_data = $this->request->param();
        $controller = '\app\common\controller\zhongzhuan'.$baiying_api_version.'\Autophonetongbu';
        $param = [
            'access_token'=>$this->access_token,
            'companyId' => $this->companyId,
        ];       
        if(!empty($request_data['jobid'])){
            $param['where'] = array('callJobId'=>$request_data['jobid']);
        }
        if(!empty($request_data['starttime'])){
            $start_time_arr = explode(',',$request_data['starttime']);
        }
        if(empty($start_time_arr)) exit('a');
        foreach ($start_time_arr as $item){
            $param['starttime'] = $item;
            $data = call_user_func_array(array($controller, 'startTongbu'),array($param));
        }

            
    }


    public function autoFenYeGetTaskPhoneByCallInstanceId(){

        $baiying_api_version = config('zhongzhuan.baiying_api_version');

        $request_data = $this->request->param();
        $controller = '\app\common\controller\zhongzhuan'.$baiying_api_version.'\Autophonetongbu1';

        $param = [
            'access_token'=>$this->access_token,
            'companyId' => $this->companyId,
        ];

        if(!empty($request_data['callInstanceId'])){
            $callInstanceId_arr = explode(',',$request_data['callInstanceId']);
        }
        if(empty($callInstanceId_arr)) exit('a');
        foreach ($callInstanceId_arr as $item){
            $param['callInstanceId'] = $item;
            $data = call_user_func_array(array($controller, 'autophonetongbubycallinstanceid'),array($param));
        }


    }




    public function autoBatchTaskYixiangCount(){
        $end_list = [];

        $request_data = $this->request->param();

        if(!empty($request_data['jobid'])){
            $calljobid = explode(',',$request_data['jobid']);
        }
        $resultQueryList = '[{"name":"客户意向等级","value":"A","name":"客户意向等级","value":"B"}]';
        foreach ($calljobid as $val) {
            $item_request_data = array('startTime'=>date("Y-m-d").' 00:00:00','callJobId'=>$val,'resultQueryList'=>$resultQueryList);
            $item_reponse_ = $this->getAiTaskDetai1($item_request_data,$this->access_token,$this->companyId);
           
            $count = db(getBaiYingDataTable())->where([
                'yixiang_value'=>['in',['A','B']],
                'callJobId'=>$val,
                'createtime'=>['>',strtotime('today')],
            ])->count();
            $end_list[$val] = [
                'total'=>$item_reponse_['data']['total'],
                'success'=>$count,
                'fail'=> $item_reponse_['data']['total'] - $count
            ];

        }
        $this->success('',$end_list);
    }


    public function autoGetTaskTongjiDetail(){

        $request_data = $this->request->param();

        if(!empty($request_data['jobid'])){
            $calljobid = explode(',',$request_data['jobid']);
        }
        foreach ($calljobid as $val) {
            $item_request_data = array('callJobId'=>$val);
            $item_reponse_ = $this->getAiTaskDetail($item_request_data,$this->access_token,$this->companyId);

        }
        $this->success('',$item_reponse_);
    }

    public static function getAiTaskDetail($request_data,$access_token,$companyId) {

        $client = new BYTokenClient($access_token);

        $method = 'byai.openapi.calljob.stat.get'; //要调用的api名称
        $api_version = '1.0.0'; //要调用的api版本号


        $my_params = ['companyId' => $companyId];
        $my_params = array_merge($my_params,$request_data);
        $my_files = [];

        $result = $client->post($method, $api_version, $my_params, $my_files);

        return $result;

    }


    public static function getAiTaskDetai1($request_data,$access_token,$companyId) {

        $client = new BYTokenClient($access_token);

        $method = 'byai.openapi.calljob.calldone.list'; //要调用的api名称
        $api_version = '1.0.0'; //要调用的api版本号


        $my_params = ['companyId' => $companyId];
        $my_params = array_merge($my_params,$request_data);
        $my_files = [];

        $result = $client->post($method, $api_version, $my_params, $my_files);

        return $result;

    }
    
    public function batchGetAiTaskPhoneDetail(){        
        $list = db(getBaiYingDataTable())->alias('a')
                ->join('by_call_detail b','a.id = b.task_phone_id','LEFT')
                ->field('a.id,a.callInstanceId')
                ->whereNull('b.status')
                ->limit(1)->select();     
        foreach ($list as $value){
            $ite_request_data = ['callInstanceId'=>$value['callInstanceId']];
            $item_reponse = $this->signelGetAiTaskPhoneDetail($ite_request_data);
            if($item_reponse['status'] == 2001){
                $success_ai_task_id = $value['id'];
            }
        }
              
        
    }
    
    
    public function signelGetAiTaskPhoneDetail($request_data){
        
        $exist_info = db('by_call_detail')->where('callInstanceId',$request_data['callInstanceId'])->find();           
        if(empty($exist_info['status']) || empty($exist_info['detail'])){
            $item_response = $this->getAiTaskPhoneDetail(['callInstanceId'=>$request_data['callInstanceId']]);
                
            if($item_response['code'] == 200){

                if(empty($exist_info)){
                    $task_phone_id = empty($request_data['task_phone_id']) ? 0 : $request_data['task_phone_id'];
                    if(empty($task_phone_id)){
                        $task_phone_id = db(getBaiYingDataTable())->where('callInstanceId',$request_data['callInstanceId'])->value('id');
                    }
                    
                    
                    
                    db('by_call_detail')->insertGetId([
                        'callInstanceId'=>$request_data['callInstanceId'],
                        'task_phone_id'=>$task_phone_id,
                        'status'=>1,
                        'detail'=> json_encode($item_response['data'],JSON_UNESCAPED_UNICODE),
                        'createtime'=>time()
                    ]);
                }else{
                    db('by_call_detail')->where('id',$exist_info['id'])->insertGetId([
                        'status'=>1,
                        'detail'=> json_encode($item_response['data'],JSON_UNESCAPED_UNICODE)
                    ]);
                }
                
                return ['status'=>2001,'data'=>json_encode($item_response['data'],JSON_UNESCAPED_UNICODE)];

            }
            return ['status'=>4000,'data'=>[]];
        }
        
        return ['status'=>2000,'data'=> $exist_info['detail']];
        
    }

    





    public function getAiTaskPhoneDetail($request_data) {
        
        $client = new BYTokenClient($this->access_token);

        $method = 'byai.openapi.callinstance.detail.get'; //要调用的api名称
        $api_version = '1.0.0'; //要调用的api版本号
        

        $my_params = ['companyId' => $this->companyId,'callInstanceId'=>$request_data['callInstanceId']];
        $my_files = [];

        $result = $client->post($method, $api_version, $my_params, $my_files);
        
        return $result;
        
    }
    
    
    
    

    
    

}
